package com.wuda.dao;

import com.wuda.bean.BookReview;
import com.wuda.utils.Base;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookReviewDao {

	UserDao userDao = new UserDao();

	/**
	 * 根据书id获取书评
	 * @param bookId 书id
	 * @return 书评列表
	 */
	public List<BookReview> getReviewsByBookId(int bookId) {
		List<BookReview> reviews = new ArrayList<>();
		Connection connection = null;
		ResultSet resultSet = null;

		try {
			connection = Base.getConnection();
			String sql = "SELECT * FROM book_review WHERE book_id = ?";
			resultSet = Base.executeQuery(connection, sql, new Object[]{bookId});

			while (resultSet.next()) {
				BookReview review = new BookReview();
				review.setReviewId(resultSet.getInt("review_id"));
				review.setUserId(resultSet.getInt("user_id"));
				review.setBookId(resultSet.getInt("book_id"));
				review.setRating(resultSet.getInt("rating"));
				review.setComment(resultSet.getString("comment"));
				review.setReviewDate(resultSet.getDate("review_date"));
				review.setUser(userDao.getUserById(review.getUserId()));
				reviews.add(review);
			}
		} catch (ClassNotFoundException | SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				Base.closeResource(connection, null, resultSet);
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}

		return reviews;
	}


	/**
	 * 添加书评
	 * @param review 书评对象
	 * @return true添加成功，false添加失败
	 */
	public boolean addBookReview(BookReview review)  {

		Connection connection = null;
		PreparedStatement pstmt = null;
		try {
			connection = Base.getConnection();
			String sql = "INSERT INTO book_review (user_id, book_id, rating, comment, review_date) VALUES (?, ?, ?, ?, ?)";
			pstmt = connection.prepareStatement(sql);

			pstmt.setInt(1, review.getUserId());
			pstmt.setInt(2, review.getBookId());
			pstmt.setInt(3, review.getRating());
			pstmt.setString(4, review.getComment());
			pstmt.setDate(5, new java.sql.Date(review.getReviewDate().getTime()));

			int result = pstmt.executeUpdate();
			return result > 0;

		} catch (Exception e ) {
			e.printStackTrace();
			return false;
		}  finally {
			try {
				Base.closeResource(connection, pstmt, null);
			} catch (SQLException e) {
				// 记录异常信息到日志文件或者其他适当的地方
				e.printStackTrace();
			}
		}




	}

}
